from odoo import fields, models, api
from odoo.exceptions import UserError

from ...functions.book_pickup_fc import BookPickupFC

from odoo.addons.rp_courier_management.models.setting.rp_courier_postal_outlet import POSTAL_TYPE
from odoo.addons.rp_courier_management.models.primary.rp_courier_mail_route import FULFILLMENT_TYPE


class RPShipOrderFulfillmentLine(models.Model):
    _name = 'rp.ship.order.fulfillment.line'
    _description = '订单头尾程明细'

    rp_ship_order_id = fields.Many2one(string='关联订单', comodel_name='rp.ship.order', ondelete='cascade')
    currency_id = fields.Many2one(string='货币单位', comodel_name='res.currency', default=lambda self: self.env.company.currency_id)

    name = fields.Char(string='名称', readonly=True)
    operation_type = fields.Selection(string='类型', selection=FULFILLMENT_TYPE, readonly=True)

    available_flag = fields.Boolean(string='可用', readonly=False)
    use_flag = fields.Boolean(string='使用', default=False)
    book_date = fields.Date(string='预约时间')
    book_time_id = fields.Many2one(string='预约时段', comodel_name='rp.book.time')
    postal_outlet_id = fields.Many2one(string='网点', comodel_name='rp.courier.postal.outlet', domain=[('type', 'in', [POSTAL_TYPE[1][0], POSTAL_TYPE[2][0]])])
    book_note = fields.Text(string='预约说明', tracking=True)

    def write(self, vals):
        state = self.rp_ship_order_id.state
        if state in ['done', 'invoiced']:
            raise UserError('订单已支付完成或已开票，拒绝进行修改！')
        return super(RPShipOrderFulfillmentLine, self).write(vals)

    @api.onchange('book_date')
    def _onchange_book_date(self):
        """ 输入时间需要大于当天 """
        if self.book_date:
            if not BookPickupFC(self.env).judge_use_date(self.book_date):
                self.update({'book_date': False})
                raise UserError('输入时间需要大于等于当天')

    @api.onchange('book_time_id')
    def _onchange_book_time_id(self):
        if self.book_time_id:
            if not BookPickupFC(self.env).judge_use_date(self.book_date, 'gt'):
                if not BookPickupFC(self.env).judge_user_time(self.book_time_id):
                    self.update({'book_time_id': False})
                    raise UserError('当天中，输入时段需要大于等于当前')


class RPShipOrderValueAddedLine(models.Model):
    _name = 'rp.ship.order.value.added.line'
    _description = '订单增值服务明细'

    rp_ship_order_id = fields.Many2one(string='关联订单', comodel_name='rp.ship.order', ondelete='cascade')

    currency_id = fields.Many2one(string='货币单位', comodel_name='res.currency', default=lambda self: self.env.company.currency_id)

    value_added_id = fields.Many2one(string='增值服务', comodel_name='rp.value.added.service', readonly=True)
    value_added_type = fields.Selection(string='类型', related='value_added_id.type', store=True)
    value_added_category = fields.Selection(string='增值服务等级', related='value_added_id.category', store=True)

    tag_price = fields.Float(string='标价', digits=(5, 3), default=0, readonly=True)
    sale_adjusted_price = fields.Float(string='销售调后价', digits=(5, 3), default=0, readonly=True)
    used_sale_price_adjust_ids = fields.Many2many(string='使用销售调价', comodel_name='rp.shipper.sale.price.adjustment', readonly=True,
                                                  relation='rp_ship_order_value_added_and_sale_price_adjustment_rel', column1='ship_order_value_added_id', column2='sale_price_adjustment_id')
    actual_price = fields.Float(string='实价', digits=(5, 3), default=0, compute='_depends_compute_actual_price', store=True)


    def write(self, vals):
        state = self.rp_ship_order_id.state
        if state in ['done', 'invoiced']:
            raise UserError('订单已支付完成或已开票，拒绝进行修改！')
        return super(RPShipOrderValueAddedLine, self).write(vals)

    @api.depends('sale_adjusted_price')
    def _depends_compute_actual_price(self):
        """ 更新实价 -> 使用销售调后价 """
        for s in self:
            s.write({'actual_price': s.sale_adjusted_price})
